import { Injectable } from '@angular/core';
import { LvConfig } from '../config';
import { LvLoadingSize } from '../types';
import { TypeUtils } from '../utils/type';

interface LvLoadingOptions {
  text?: string;
  size?: LvLoadingSize | number;
}

@Injectable({
  providedIn: 'root',
})
export class LoadingService {
  loadingContainer;

  className = 'lv-loading-gloabl-container';

  public assetsPrefixPath = LvConfig.assetsPrefixPath;

  constructor() {
    const div = document.createElement('div');
    div.className = this.className;

    div.innerHTML = `
      <div class="lv-loading-content">
        <div class="lv-loading-loader-container">
          <img class="lv-icon-loading" src="${this.assetsPrefixPath}assets/webp/blue.png" alt="icon-loading" />
        </div>
        <p class="lv-loading-text">Loading...</p>
      </div>
      <div class="lv-loading-mask"></div>
    `;

    this.loadingContainer = div;
  }

  get loadingText(): string {
    return (
      {
        'zh-cn': '加载中...',
        'en-us': 'Loading...',
      }[LvConfig.language] || 'Loading...'
    );
  }

  hide(): void {
    if (document.body.querySelector(`body > .${this.className}`)) {
      document.body.removeChild(this.loadingContainer);
    }
  }

  show(options?: string | LvLoadingOptions): void {
    const sizeClassMap = {
      mini: 'lv-loading-icon-size-mini',
      small: 'lv-loading-icon-size-small',
      medium: 'lv-loading-icon-size-medium',
      default: 'lv-loading-icon-size-default',
    };
    let text;
    let size;

    if (TypeUtils.isObject(options)) {
      text = (options as LvLoadingOptions)?.text;
      size = (options as LvLoadingOptions)?.size;
    } else {
      text = options; // 适配原有用法，推荐使用object
    }

    // 更新loading text
    this.loadingContainer.querySelector('.lv-loading-text').textContent = text || this.loadingText;

    this.loadingContainer.className =
      size && !TypeUtils.isNumber(size) ? `${this.className} ${sizeClassMap[size]}` : this.className;

    if (size) {
      this.loadingContainer.querySelector('.lv-loading-loader-container').style.width = TypeUtils.isNumber(size)
        ? `${size}px`
        : null;
      this.loadingContainer.querySelector('.lv-loading-loader-container').style.height = TypeUtils.isNumber(size)
        ? `${size}px`
        : null;
    }

    document.body.appendChild(this.loadingContainer);
  }
}
